<template>
  <div v-loading="loading">
    <el-tabs v-model="currentTab" type="border-card" class="j-tabs" @tab-change="onTabChange">
      <el-tab-pane name="1" label="Residential Proxies">
        <div class="proxy-form mt-0">
          <div class="form-main">
            <div class="form">
              <el-form label-width="144px" :model="proxyForm" ref="proxyFormRef" :rules="rules" size="large">
                <el-form-item label="Country/Place" prop="country_code">
                  <el-select
                    v-model="proxyForm.country_code"
                    filterable
                    clearable
                    placeholder="Please select a country/place"
                    class="full-width"
                    @change="onCountryChange"
                  >
                    <el-option v-for="item in countryList" :key="item.code" :label="item.name" :value="item.code" />
                  </el-select>
                </el-form-item>
                <el-form-item label="IP type" prop="line_type">
                  <el-radio-group v-model="proxyForm.line_type" @change="onLineTypeChange">
                    <el-radio value="2" size="large" border>Standard</el-radio>
                    <el-radio value="3" size="large" border>Advanced</el-radio>
                  </el-radio-group>
                  <div class="form-item-tips">
                    <el-icon size="18px" color="#999">
                      <QuestionFilled />
                    </el-icon>
                    <span v-if="proxyForm.line_type == '2'">High-purity IP, meeting the needs of most business scenarios</span>
                    <span v-else-if="proxyForm.line_type == '3'"
                      >More pure proxy address, highly hidden and enjoy high cost performance</span
                    >
                  </div>
                </el-form-item>
                <el-form-item label="Business purpose" prop="Business purpose">
                  <el-select
                    v-model="proxyForm.business"
                    filterable
                    clearable
                    placeholder="Please select a business purpose"
                    class="full-width"
                    @change="onBusinessChange"
                  >
                    <el-option v-for="item in businessList" :key="item" :label="item" :value="item" />
                  </el-select>
                </el-form-item>
                <el-form-item label="Package type" prop="days">
                  <el-radio-group v-model="proxyForm.days">
                    <el-radio value="30" size="large" border>30days</el-radio>
                    <el-radio value="60" size="large" border>60days</el-radio>
                    <el-radio value="90" size="large" border>90days</el-radio>
                    <el-radio value="360" size="large" border>360days</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="Purchase quantity" prop="quantity">
                  <el-input
                    v-model.number="proxyForm.quantity"
                    type="number"
                    :min="1"
                    autocomplete="off"
                    placeholder="Please enter the purchase quantity"
                  />
                </el-form-item>
                <el-form-item label="Payment type" prop="pay_way">
                  <el-radio-group v-model="proxyForm.pay_way" class="pay-way-list">
                    <el-radio label="alipay" border>
                      <span class="form-pay-icon">
                        <img src="@/assets/ipx-proxy_160.png" class="img" />
                        <span>AliPay</span>
                      </span>
                    </el-radio>
                    <el-radio label="card" border>
                      <span class="form-pay-icon">
                        <img src="@/assets/ipx-proxy_150.png" class="img" />
                        <span>Credit Card</span>
                      </span>
                    </el-radio>
                    <el-radio label="usdt" border>
                      <span class="form-pay-icon">
                        <img src="@/assets/ipx-proxy_156.png" class="img" />
                        <span>USDT</span>
                      </span>
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="Total amount" prop="quantity">
                  <div class="form-amount">
                    <span>$</span>
                    <strong>{{ amount }}</strong>
                  </div>
                </el-form-item>
                <el-form-item label="" label-width="10px">
                  <div class="form-submit-tips">
                    <span>· The proxy provided by IPXProxy <strong>is only for use outside the Chinese mainland and is subject to local network regulation</strong>. Please use it legally and in compliance with regulations.</span>
                    <span>· After the agent sells, <strong>returns and exchanges are not supported</strong>. Please confirm the type and region of the agent before purchasing to avoid wrong purchases.</span>
                  </div>
                </el-form-item>
                <el-form-item>
                  <div style="white-space: nowrap">
                    <el-button
                      class="primary-btn"
                      style="width: 134px"
                      type="primary"
                      :disabled="loading"
                      :loading="loading"
                      @click="onSubmit(proxyFormRef)"
                      >Pay Now</el-button
                    >
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="form-tips">
            <p class="title">Q: What are static residential proxies?</p>
            <p class="info">A: Static residential proxies provide fixed IP addresses from actual residential networks, offering long-term stability and high anonymity.</p>

            <p class="title">Q: When should you use static residential proxies?</p>
            <p class="info">A: They are best for tasks requiring a consistent IP address, such as managing multiple social media accounts, accessing region-specific services, and maintaining continuous online sessions.</p>

            <p class="title">Q: How do you set up static residential proxies?</p>
            <p class="info">A: Purchase a proxy plan and configure your application with the provided proxy IP, port, username, and password.</p>

            <p class="title">Q: How can I get a free trial of static residential proxies?</p>
            <p class="info">A: Static products currently do not offer any free trial services. For dynamic residential lines, users can receive a free traffic package for testing after registration and activation.</p>

            <p class="title">Q: Are static residential proxies effective for web scraping?</p>
            <p class="info">A: They are ideal for web scraping tasks that require a stable IP to avoid triggering anti-scraping mechanisms, ensuring uninterrupted data collection.</p>

            <p class="title">Q: Can I use your lines to access blocked websites?</p>
            <p class="info">A: No! lines have blocked all access from domestic IPs. Before using the lines, you need to prepare your own overseas environment.</p>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="2" label="Usage Record">
        <Record ref="recordRef" :countryList="countryList" :businessList="businessList" @page-loading="onPgeLoading" />
      </el-tab-pane>
    </el-tabs>

    <Pay ref="payRef" payType="static" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, nextTick } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { staticRegionApi, businessApi } from '@/api/index';
  import type { FormInstance, FormRules } from 'element-plus';
  import { QuestionFilled } from '@element-plus/icons-vue';
  import Record from './components/record.vue';
  import { calculatePrice } from '@/utils/index';
  import Pay from '../pay/en.vue';

  const route = useRoute();
  const router = useRouter();
  const userStore = useUserStore();

  const getUserInfo = computed(() => {
    let userInfo = userStore.getUserInfo || {};
    return userInfo;
  });

  const amount = computed(() => {
    return calculatePrice(proxyForm.line_type, proxyForm.days, proxyForm.quantity);
  });

  const props = defineProps<{
    data: Array;
  }>();

  const emits = defineEmits<{
    (event: 'confirm'): void;
    (event: 'page-change'): void;
  }>();

  const recordRef = ref();
  const payRef = ref();
  const loading = ref(false);
  const currentTab = ref('1');
  const proxyFormRef = ref<FormInstance>();
  const proxyForm = reactive({
    country_code: '',
    country_code_str: '',
    line_type: '2',
    line_type_str: '标准',
    business: '',
    business_str: '',
    days: '30',
    quantity: 1,
    pay_way: 'alipay',
  });
  const rules = reactive<FormRules>({
    country_code: [{ required: true, message: 'Please select a country/place', trigger: 'change' }],
    line_type: [{ required: true, message: 'Please select a IP type', trigger: 'change' }],
    business: [{ required: true, message: 'Please select a business purpose', trigger: 'change' }],
    days: [{ required: true, message: 'Please select a package', trigger: 'change' }],
    quantity: [{ required: true, message: 'Please enter purchase quantity', trigger: 'change' }],
    pay_way: [{ required: true, message: 'Please select a payment method', trigger: 'change' }],
  });

  const countryList = ref([]);
  const businessList = ref([]);

  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        onBuy(proxyForm);
      }
    });
  };

  const onReset = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
  };

  const onTabChange = (val) => {
    if (val == '2') {
      recordRef.value.onPageChange('staticProxy', 1);
    }
  };

  const onCountryChange = (val) => {
    let obj = countryList.value.find((v) => (v.code == val));
    proxyForm.country_code_str = obj.name || '';
  };

  const onLineTypeChange = (val) => {
    if (val == 2) {
      proxyForm.line_type_str = 'Standard';
    } else if (val == 3) {
      proxyForm.line_type_str = 'Advanced';
    }
  };

  const onBusinessChange = (val) => {
    let str = businessList.value.find((v) => (v == val));
    proxyForm.business_str = str || '';
  };

  const getRegion = async (type) => {
    staticRegionApi({})
      .then((res) => {
        if (res.data) {
          if (type == 'country') {
            countryList.value = res.data;
          }
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const getBusiness = async () => {
    businessApi({})
      .then((res) => {
        if (res.data) {
          businessList.value = res.data;
        }
      })
      .catch((err) => {
        console.log('err', err);
        ElMessage.error(err.message);
      });
  };

  const onPgeLoading = (val) => {
    loading.value = val;
  };

  const onBuy = (item) => {
    emits('log', item);
    payRef.value.onBuy({
      ...item,
      amount,
      payType: 'static',
    });
  };

  onMounted(() => {
    getRegion('country');
    getBusiness();
  });
</script>

<style scoped lang="scss">
  .proxy-form {
    min-width: 1264px;
    justify-content: center;
  }

  .form-submit-tips {
    min-height: 18px;
    padding: 0;
    margin: 0 0 0 134px;
    font-size: 14px;
    color: #666;
    line-height: 24px;

    span {
      display: block;
    }

    strong {
      color: #fa1801;
    }
  }

  .form-item-tips {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    min-height: 18px;
    padding: 0;
    margin: 0 0 0 20px;
    border-radius: 0;
    background: #fff;
    font-size: 14px;
    color: #999;
    line-height: 18px;

    span {
      padding-left: 5px;
    }
  }

  .form-amount {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    height: 28px;
    font-size: 20px;
    color: #ff7928;
    font-weight: bold;
    line-height: 28px;

    strong {
      font-size: 28px;
      margin-top: -2px;
      margin-left: 4px;
    }
  }

  .form-pay-icon {
    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
    height: 21px;
    vertical-align: middle;
  }
</style>
